import {h, defineComponent, watch} from 'vue'
import {AutoComplete, Form} from 'ant-design-vue';
import { useVModel } from '@vueuse/core'
import { cloneDeep,filter } from 'lodash'
import {arrFind} from "@/utils";
import useRemoteOptions from '@/hook/remoteOptions.js'
export default defineComponent({
    name:'ExAutoComplete',
    props:{
        remote:Object,
        options:Array,

    },
    emits:['update:options'],
    setup(props,ctx){
        const formItemContext = Form.useInjectFormItemContext();
        watch(()=>ctx.attrs.value,value=>{
            formItemContext.onFieldChange()
        })
        const options  = useVModel(props,'options',ctx.emit)
        const originOptions = cloneDeep(options.value)
        const {remoteOptionsDebounce} = useRemoteOptions(props,options)
        function filterOption(query){
            setTimeout(()=>{
                options.value = filter(originOptions,function (option){
                    return option.value.toUpperCase().indexOf(query.toUpperCase()) >= 0;
                })
            })
        }
        return {
            remoteOptionsDebounce,
            options,
            filterOption,
            originOptions
        }
    },
    render(e){
        let props = Object.assign({},e.$attrs)
        if(e.remote){
            props.onFocus = ()=>{
                if(!e.$attrs.value){
                    this.remoteOptionsDebounce('')
                }
            }
        }
        props.onSearch = (query)=>{
            if(e.remote) {
                this.remoteOptionsDebounce(query)
            }else{
                this.filterOption(query)
            }
        }
        if(!e.$attrs.options && e.options){
           props.options = e.options
        }
        return h(AutoComplete, props, e.$slots)
    }
})